package com.caption.auth.secuity.sms;

import com.caption.auth.secuity.entity.SysUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

/**
 * @description: 短信验证码验证登录(模拟用户名密码登录方式)
 * @author: 码农
 * @date: 2021-12-31 20:07:16
 */
@Slf4j
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private SmsCodeDetailsServiceImpl userDetailsService;

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(SmsCodeDetailsServiceImpl userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        String mobile = (String) authenticationToken.getPrincipal();
        log.info("手机号验证码登录{}", mobile);
        SysUserDetails sysUserDetails = userDetailsService.loadUserByUsername(mobile);
        //鉴权成功，重新new一个有权限的SmsCodeAuthenticationToken
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(sysUserDetails, sysUserDetails.getAuthorities());
        authenticationResult.setDetails(sysUserDetails);
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // 判断 authentication 是不是 SmsCodeAuthenticationToken 的子类或子接口
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
